<template>
  <div class="app-container" v-loading="loading" element-loading-text="数据加载中" element-loading-spinner="el-icon-loading">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch">
      <el-form-item label="工单编号" prop="workorderCode">
        <el-input v-model="queryParams.workorderCode" placeholder="请输入工单编号" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>

      <!-- add begin by zyj 2024/10/18 -->
      <el-form-item label="工单类型" prop="orderType">
        <el-select v-model="queryParams.orderType" placeholder="请选择工单类型" clearable @keyup.enter.native="handleQuery">
          <el-option v-for="item, index in dict.type.mes_order_type" :key="index" :label="item.label" :value="item.value"></el-option>
        </el-select>
      </el-form-item>
      <!-- add end by zyj 2024/10/18 -->
      <el-form-item label="流程状态" prop="workflowStatus">
        <el-select v-model="queryParams.workflowStatus" placeholder="请选择流程状态" clearable>
          <el-option v-for="dict in dict.type.workflow_status" :key="dict.value" :label="dict.label" :value="Number(dict.value)"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="产品编号" prop="productCode">
        <el-input v-model="queryParams.productCode" placeholder="请输入产品编号" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="产品名称" prop="productName">

        <!-- edit begin by zyj 2024/10/17 产品名称支持模糊搜索下拉-->
        <!-- <el-input
          v-model="queryParams.productName"
          placeholder="请输入产品名称"
          clearable
          @keyup.enter.native="handleQuery"
        />-->
        <el-select filterable clearable placeholder="请输入产品名称" v-model="queryParams.productName" @keyup.enter.native="handleQuery" remote @clear="onClearProductName" :loading="productNameListLoading" :remote-method="remoteGetProductNameList">
          <el-option v-for="(item, index) in productNameList" :key="index" :label="item" :value="item"></el-option>
        </el-select>
        <!-- edit end by zyj 2024/10/17 产品名称支持模糊搜索下拉-->
      </el-form-item>
      <el-form-item label="单据日期" prop="fDate">
        <el-date-picker clearable v-model="queryParams.fDate" type="date" value-format="yyyy-MM-dd" placeholder="请选择需求日期"></el-date-picker>
      </el-form-item>
      <!-- <el-form-item label="bom版本是否变化" prop="versionChangeState">
        <el-checkbox :true-label="1" :false-label="0" v-model="queryParams.versionChangeState"></el-checkbox>
      </el-form-item> -->
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleSet" v-hasPermi="['produce:workorder:syncData']">同步数据</el-button>
      </el-col>
      <el-col :span="1.5">
        <!-- 2024-12-18 djj 新增 用料清单查询 按钮 -->
        <el-dropdown @command="handleCommand">
          <el-button type="primary" plain size="mini">业务查询<i class="el-icon-arrow-down el-icon--right"></i></el-button>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item command="1">用料清单查询</el-dropdown-item>
            <el-dropdown-item command="2">物料出库查询</el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
      </el-col>
      <!-- <el-col :span="1.5">
             <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
               v-hasPermi="['mes:pro:workorder:add']">新增</el-button>
      </el-col>-->
      <!--      <el-col :span="1.5">-->
      <!--        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"-->
      <!--          v-hasPermi="['mes:pro:workorder:edit']">修改</el-button>-->
      <!--      </el-col>-->
      <!--      <el-col :span="1.5">-->
      <!--        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"-->
      <!--          v-hasPermi="['mes:pro:workorder:remove']">删除</el-button>-->
      <!--      </el-col>-->
      <!-- <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['mes:pro:workorder:export']"
        >导出</el-button>
      </el-col>-->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table ref="curdRef" class="workorder-table" :data="workorderList" row-key="workorderId" default-expand-all :tree-props="{ children: 'children', hasChildren: 'hasChildren' }" height="calc(100vh - 310px)" highlight-current-row @current-change="handleCurrentChange">
      <el-table-column label="序号" align="center" width="50px">
        <template slot-scope="scope">
          <span>{{ scope.$index + 1 }}</span>
        </template>
      </el-table-column>
      <el-table-column label="生产工单id" align="center" prop="workorderId" width="110"></el-table-column>
      <el-table-column label="工单编号" width="120" align="center" prop="billNo">
        <template slot-scope="scope">
          <el-button size="mini" type="text" @click="handleView(scope.row)">{{
            scope.row.billNo }}</el-button>
        </template>
      </el-table-column>
      <el-table-column label="单据日期" align="center" prop="fDate" width="160"></el-table-column>
      <el-table-column label="类型" align="center" prop="orderType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.mes_order_type" :value="scope.row.orderType" />
        </template>
      </el-table-column>
      <el-table-column label="工单状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.mes_workorder_status" :value="scope.row.status" />
        </template>
      </el-table-column>

      <el-table-column label="流程状态" align="center" prop="workflowStatus">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.workflow_status" :value="scope.row.workflowStatus" />
        </template>
      </el-table-column>
      <el-table-column label="物料编码" width="150" align="center" prop="productCode" />
      <el-table-column label="物料名称" width="180" align="center" prop="productName" />
      <el-table-column label="规格型号" width="220" align="center" prop="productSpc" />
      <el-table-column label="单位" align="center" prop="unitName" />
      <el-table-column label="工单数量" align="center" prop="quantity" />
      <el-table-column label="已生产数量" align="center" width="100px" prop="quantityProduced" />
      <el-table-column label="批次号" align="center" width="150px">
        <template slot-scope="scope">
          <span v-if="scope.row.batchName != null">{{
            scope.row.batchName
          }}</span>
        </template>
      </el-table-column>
      <el-table-column label="领料状态" align="center" width="100px">
        <template slot-scope="scope">
          <span>
            {{
              scope.row.isIssue == "0"
                ? "未领料"
                : scope.row.isIssue == "1"
                  ? "全部领料"
                  : scope.row.isIssue == "2"
                    ? "部分领料"
                    : "--"
            }}
          </span>
        </template>
      </el-table-column>
      <!-- <el-table-column label="录入原因" align="center" prop="inputReason" >
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_input_reason" :value="scope.row.inputReason"/>
        </template>
      </el-table-column> -->
      <el-table-column label="操作" width="300px" align="center" fixed="right" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <!-- add begin by zyj 2024/10/22 工艺路径审核-->
          <el-button size="mini" type="text" @click="toRouteAudit(scope.row)" v-if="scope.row.status == 3 && scope.row.workflowStatus == '1'" v-hasPermi="['produce:technologyPath:audit']">
            工艺路径审核
          </el-button>
          <!-- add end by zyj 2024/10/22 工艺路径审核-->

          <el-button size="mini" type="text" icon="el-icon-edit" v-show="scope.row.status == 4 ||
            scope.row.status == 5 ||
            scope.row.status == 6 ||
            scope.row.status == 7
            " @click="toWorkingRecord(scope.row)" v-hasPermi="['produce:workHour:fillIn']">工时填报</el-button>
          <el-button size="mini" type="text" icon="el-icon-edit" v-if="scope.row.status == 3 && scope.row.workflowStatus == '1'" @click="
              handleUpdateRoute(scope.row, '1', '生产工单_工艺维护', 'confirm')
              " v-hasPermi="['produce:technologyPath:edit']">工艺维护</el-button>
          <el-button size="mini" type="text" icon="el-icon-edit" v-if="
            (scope.row.status == 3 || scope.row.status == 8) &&
            scope.row.workflowStatus == '2' &&
            scope.row.routeStatus == 1
          " @click="
            handleUpdateRoute(scope.row, '2', '生产工单_确认生产', 'confirm')
            " v-hasPermi="['produce:workorder:confirm']">确认生产</el-button>
          <!-- <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            v-if="
              (scope.row.isIssue == 0 || scope.row.isIssue == 2) &&
              (scope.row.status == 8 ||
                scope.row.status == 3 ||
                scope.row.status == 4) &&
              (scope.row.workflowStatus == '3' ||
                scope.row.workflowStatus == '4' ||
                scope.row.workflowStatus == '5' ||
                scope.row.workflowStatus == '7' ||
                scope.row.workflowStatus == '2')
            "
            @click="permissions(scope.row, '生产工单_生产领料', 'picking')"
            v-hasPermi="['mes:pro:workorder:edit']"
            >生成领料单</el-button
          > -->
          <el-button size="mini" type="text" icon="el-icon-edit" v-if="
            (scope.row.isIssue == 0 || scope.row.isIssue == 2) &&
            (scope.row.status == 8 ||
              scope.row.status == 3 ||
              scope.row.status == 4) &&
            (scope.row.workflowStatus == '3' ||
              scope.row.workflowStatus == '4' ||
              scope.row.workflowStatus == '5' ||
              scope.row.workflowStatus == '7' ||
              scope.row.workflowStatus == '2')
          " @click="handleRequisition(scope.row)" v-hasPermi="['produce:materialOrder:generate']">生成领料单</el-button>
          <el-button size="mini" type="text" icon="el-icon-edit" v-if="
            (scope.row.workflowStatus == '1' ||
              scope.row.workflowStatus == '2' ||
              scope.row.workflowStatus == '3') &&
            ((scope.row.status == 4 && scope.row.isIssue != 0) ||
              (scope.row.routeStatus == 1 && scope.row.status == 3) ||
              scope.row.status == 8)
          " @click="handlePushDown(scope.row)" v-hasPermi="['produce:workorder:push']">下推</el-button>
          <el-button size="mini" type="text" icon="el-icon-edit" v-if="scope.row.status == 4" @click="handleDebriefing(scope.row);" v-hasPermi="['produce:reportOrder:generate']">生成汇报单</el-button>
          <el-button size="mini" type="text" icon="el-icon-edit" @click="
            handleUpdateRoute(scope.row, '3', '生产工单_申请延期', 'confirm')
            " v-hasPermi="['produce:workorder:postpone']">任务延期</el-button>
          <el-button size="mini" type="text" icon="el-icon-edit" v-if="
            scope.row.status == 4 &&
            (scope.row.runStatus == 0 || scope.row.runStatus == null)" @click="endQuery(scope.row)" v-hasPermi="['produce:workorder:discontinued']">产线停产</el-button>
          <el-button size="mini" type="text" icon="el-icon-edit" v-if="scope.row.status == 4 && scope.row.runStatus == 1" @click="updateRunStatus(scope.row)" v-hasPermi="['produce:workorder:recover']">恢复生产</el-button>
          <el-button size="mini" type="text" @click="endQuery(scope.row)" v-hasPermi="['produce:workorder:stop']">终止</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" v-if="scope.row.status == 0" @click="handleDelete(scope.row)" v-hasPermi="['produce:workorder:remove']">删除</el-button>
          <!-- <el-button
            size="mini"
            type="text"
            icon="el-icon-printer"
            @click="print(scope.row)"
            v-hasPermi="['mes/pro/workorderSn:workorderSn:print']"
          >打印条码</el-button>-->
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleBom(scope.row, '生产工单_bom变更', 'bom')" v-hasPermi="['produce:materialOrder:change']">物料清单变更</el-button>

          <!-- add begin by zyj 2024/10/29 在生产工单 操作列，增加“生产补料” -->
          <el-button size="mini" type="text" @click="toSupplyDetail(scope.row)" v-if="scope.row.status == 4 && (scope.row.runStatus == 0 || scope.row.runStatus == null)" v-hasPermi="['produce:material:replenish']">
            生产补料
          </el-button>
          <!-- add end by zyj 2024/10/29 在生产工单 操作列，增加“生产补料” -->
          <!-- 2024/11/15 新增 生产退料 按钮 -->
          <el-button size="mini" type="text" icon="el-icon-edit" @click="getBackProduction(scope.row)" v-hasPermi="['produce:material:return']">生产退料</el-button>
          <!-- 2024-12-2  新增按钮现在，只有“返工生产”的工单  才显示 “成品改制” 和“改制详情”按钮  -->
          <!-- 2024-11-27 djj 新增 成品改制 按钮 -->
          <el-button size="mini" type="text" icon="el-icon-edit" v-if="scope.row.orderType == 2 && (!scope.row.remakeStatus || scope.row.remakeStatus == 1)" @click="getFinishedProductReform(scope.row)" v-hasPermi="['produce:workorder:transform']">成品改制</el-button>
          <!-- 2024-11-29 djj 新增 改制详情 按钮 -->
          <el-button size="mini" type="text" icon="el-icon-edit" v-if="scope.row.orderType == 2 && (scope.row.remakeStatus == 1 || scope.row.remakeStatus == 2)" @click="getFinishedProductReformInfo(scope.row)" v-hasPermi="['produce:transform:view']">改制详情</el-button>
          <!-- 2024-12-19 djj 新增 复制BOM版本 按钮;
           工单类型为“返工生产”，同时结果集 bomItemCode 返回为空时，操作列显示“复制BOM版本” -->
          <el-button size="mini" type="text" icon="el-icon-edit" v-if="scope.row.orderType == 2 && !scope.row.bomItemCode" @click="getCopyBom(scope.row)" v-hasPermi="['produce:proBom:copy']">复制BOM版本</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" :page-sizes="[50, 100, 200, 300, 400, 500]" @pagination="getList" />
    <!-- 查看详情 -->
    <el-drawer :title="title" :visible.sync="openDetail" size="80%" @close="cancelDetail">
      <div style="padding: 0 20px">
        <el-tag size="large" style="font-size: 20px">基本信息</el-tag>
        <hr />
        <el-row :gutter="20">
          <el-col :span="8">
            <div class="grid-content bg-purple">
              <span>工单编号：</span>
              <span>{{ form.workorderCode }}</span>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="grid-content bg-purple">
              <span>工单类型：</span>
              <span>
                <dict-tag :options="dict.type.mes_order_type" :value="form.orderType" />
              </span>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="grid-content bg-purple">
              <span>工单状态：</span>
              <span>
                <dict-tag :options="dict.type.mes_workorder_status" :value="form.status" />
              </span>
            </div>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="8">
            <div class="grid-content bg-purple">
              <span>批次号：</span>
              <span>{{ form.batchName }}</span>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="grid-content bg-purple">
              <span>工单数量：</span>
              <span>{{ form.quantity }}</span>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="grid-content bg-purple">
              <span>单位：</span>
              <span>{{ form.unitName }}</span>
            </div>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="8">
            <div class="grid-content bg-purple">
              <span>生产车间：</span>
              <span>{{ form.workshopName }}</span>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="grid-content bg-purple">
              <span>生产产线：</span>
              <span>{{ form.lineName }}</span>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="grid-content bg-purple">
              <span>BOMID：</span>
              <span>{{ form.bomId }}</span>
            </div>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="8">
            <div class="grid-content bg-purple">
              <span>物料编码：</span>
              <span>{{ form.productCode }}</span>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="grid-content bg-purple">
              <span>物料名称：</span>
              <span>{{ form.productName }}</span>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="grid-content bg-purple">
              <span>BOM版本：</span>
              <span>{{ form.bomItemCode }}</span>
            </div>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="8">
            <div class="grid-content bg-purple">
              <span>计划开始时间：</span>
              <span>{{ form.fPlanStartDate }}</span>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="grid-content bg-purple">
              <span>计划完工时间：</span>
              <span>{{ form.fPlanFinishDate }}</span>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="grid-content bg-purple">
              <span>规格型号：</span>
              <span>{{ form.productSpc }}</span>
            </div>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="8">
            <div class="grid-content bg-purple"></div>
          </el-col>
          <el-col :span="8">
            <div class="grid-content bg-purple"></div>
          </el-col>
          <el-col :span="8">
            <div class="grid-content bg-purple">
              <span>实际开始时间：</span>
              <span>{{ form.actualStartTime }}</span>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="grid-content bg-purple">
              <span style="color: #fff">{{ "占位" }}</span>
              <span style="color: #fff">{{ "占位" }}</span>
            </div>
          </el-col>

          <el-col :span="8">
            <div class="grid-content bg-purple">
              <span>物料类型：</span>
              <span>{{
                form.productType == "DC"
                  ? "直流充电桩"
                  : form.productType == "AC"
                    ? "交流充电桩"
                    : form.productType == "PCBA"
                      ? "PCBA"
                      : form.productType == "WR"
                        ? "线材"
                        : form.productType == "VM"
                          ? "车载"
                          : "--"
              }}</span>
            </div>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="8">
            <div class="grid-content bg-purple">
              <span>工艺路径编号：</span>
              <span>{{ form.routeCode }}</span>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="grid-content bg-purple">
              <span>工艺路径：</span>
              <span>{{ form.routeName }}</span>
            </div>
          </el-col>
        </el-row>
        <el-tag size="large" style="font-size: 20px; margin-bottom: 10px; margin-top: 10px">操作记录</el-tag>
        <hr />
        <CheckRecord v-if="checkrecordOpen" ref="checkrecords"></CheckRecord>

        <el-tag size="large" style="font-size: 20px; margin-bottom: 10px; margin-top: 10px">工艺维护数据</el-tag>
        <hr />
        <el-tabs type="border-card" v-if="processList.length > 0" v-model="activeName" @tab-click="handleClick">
          <el-tab-pane v-for="(process, index) in processList" :key="process.processId" :label="process.processName" :name="'routeproductbomDetailRef' + index">
            <RouteproductbomDetail ref="routeproductbomDetailRef" :routeId="form.routeId" :productId="form.productId" :bomItemCode="form.bomItemCode" :processId="process.processId" :buttonType="2" :optType="optType" :workorderId="form.workorderId">
            </RouteproductbomDetail>
          </el-tab-pane>
        </el-tabs>
        <el-empty v-else description="暂无数据" image-size="50"></el-empty>
        <el-tag size="large" style="font-size: 20px; margin-bottom: 10px; margin-top: 10px">返还件</el-tag>
        <hr />
        <ReturnPiece :workorderId="form.workorderId" :workorderCode="form.workorderCode"></ReturnPiece>
        <el-tag size="large" style="font-size: 20px; margin-bottom: 10px; margin-top: 10px">生产领料单</el-tag>
        <hr />
        <Replenishment :workorderId="form.workorderId"></Replenishment>
        <el-tag size="large" style="font-size: 20px; margin-bottom: 10px; margin-top: 10px">生产汇报单</el-tag>
        <hr />
        <ReportForm :workorderId="form.workorderId"></ReportForm>
        <el-tag size="large" style="font-size: 20px; margin-bottom: 10px; margin-top: 10px">生产退料单</el-tag>
        <hr />
        <Returned :workorderId="form.workorderId" :workorderCode="form.workorderCode"></Returned>
        <el-tag size="large" style="font-size: 20px; margin-bottom: 10px; margin-top: 10px">生产补料单</el-tag>
        <hr />
        <Material :workorderId="form.workorderId" :workorderCode="form.workorderCode"></Material>
      </div>
    </el-drawer>

    <!-- 工艺维护//确认生产 弹窗 -->
    <el-dialog :title="title" :visible.sync="openCraft" width="75%" append-to-body>
      <el-form ref="carftForm" :model="carftForm" :rules="carftForm.doType == '1'
        ? rules
        : carftForm.doType == '2'
          ? rulesc
          : rulesa
        " label-width="110px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="工单编号" prop="workorderCode">
              <el-input v-model="carftForm.workorderCode" placeholder="请输入工单编号" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="单据状态" prop="status">
              <el-select v-model="carftForm.status" disabled placeholder="请选择单据状态">
                <el-option v-for="dict in dict.type.mes_workorder_status" :key="dict.value" :label="dict.label" :value="Number(dict.value)"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="产品编号" prop="productCode">
              <el-input v-model="carftForm.productCode" placeholder="请选择产品" disabled></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="产品名称" prop="productName">
              <el-input v-model="carftForm.productName" placeholder="请选择产品" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="生产车间" prop="workshopId">
              <el-select v-model="carftForm.workshopId" placeholder="请选择生产车间" @change="selectTrigger(carftForm.workshopId)" :disabled="carftForm.doType == '1' || carftForm.doType == '3'
                  ? true
                  : false
                  ">
                <el-option v-for="item in workshopList" :key="item.workshopId" :label="item.workshopName" :value="item.workshopId"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="生产产线" prop="lineId">
              <el-select v-model="carftForm.lineId" multiple placeholder="请选择产线" :disabled="carftForm.doType == '1' || carftForm.doType == '3'
                ? true
                : false
                ">
                <el-option v-for="item in productionlineList" :key="item.lineId" :label="item.lineName" :value="item.lineId"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="产品类型" prop="productType">
              <el-select v-model="carftForm.productType" placeholder="请选择产品类型" :disabled="carftForm.doType == '1' || carftForm.doType == '3'
                ? true
                : false
                ">
                <el-option label="直流充电桩" value="DC"></el-option>
                <el-option label="交流充电桩" value="AC"></el-option>
                <el-option label="PCBA" value="PCBA"></el-option>
                <el-option label="线材" value="WR"></el-option>
                <el-option label="车载" value="VM"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="工单工艺路线" prop="routeName">
              <el-input v-model="carftForm.routeName" placeholder="请输入工单工艺路线" disabled />
              <!--              <el-select v-model="carftForm.routeId"  placeholder="请选择" >-->
              <!--                <el-option v-for="item in carftList" :key="item.routeId" :label="item.carftName" :value="item.routeId">-->
              <!--                </el-option>-->
              <!--              </el-select>-->
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="计划开工时间" prop="fPlanStartDate">
              <el-date-picker v-model="carftForm.fPlanStartDate" type="date" value-format="yyyy-MM-dd" placeholder="选择日期时间" disabled></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="计划完工时间" prop=" fPlanFinishDate">
              <el-date-picker v-model="carftForm.fPlanFinishDate" type="date" value-format="yyyy-MM-dd" placeholder="选择日期时间" disabled></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="实际开工时间" prop="actualStartTime">
              <el-date-picker v-model="carftForm.actualStartTime" type="date" placeholder="选择日期时间" value-format="yyyy-MM-dd" :disabled="carftForm.doType == '1' || carftForm.doType == '3'
                  ? true
                  : false
                  "></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="延期时间" prop="delayDate">
              <el-date-picker v-model="carftForm.delayDate" value-format="yyyy-MM-dd" type="date" placeholder="选择日期时间" :disabled="carftForm.doType != '3' ? true : false"></el-date-picker>
            </el-form-item>
          </el-col>
          <!-- 2024-12-2 begin 增加是否改制选项，参数名称isRemake，1-是 0-否 -->
          <el-col :span="8">
            <el-form-item label="是否改制" prop="isRemake">
              <el-switch v-model="carftForm.isRemake" :active-value="1" :inactive-value="0">
              </el-switch>
            </el-form-item>
          </el-col>
          <!-- 2024-12-2 end  -->
        </el-row>
      </el-form>
      <el-tag size="large" style="font-size: 20px; margin-bottom: 10px; margin-top: 10px">工艺维护数据</el-tag>
      <el-cascader v-if="this.optionsChildren.length != 0" v-model="value" :options="optionsChildren" placeholder="请选择工艺模板" @change="handleChange"></el-cascader>
      <hr />
      <!-- doType: 1、工艺维护 2、确认生产 3、申请延期 -->
      <el-tabs type="border-card" v-if="processList.length > 0" v-model="activeName2" @tab-click="handleClick2">
        <el-tab-pane v-for="(process, index) in processList" :key="index" :label="process.processName" :name="routeproductbomRefType + index">
          <RouteproductMain v-if="carftForm.doType == '1'" ref="productbom" :carftForm="carftForm" :routeId="carftForm.routeId" :productId="carftForm.productId" :workorderCode="carftForm.workorderCode" :processId="process.processId" :processName="process.processName" :processCode="process.processCode" :buttonType="carftForm.doType" :optType="optType" @backEndData="getSubassembly" :subassemblyList="subassemblyList" :bomItemCode="carftForm.bomItemCode" :workorderId="carftForm.workorderId">
          </RouteproductMain>
          <Routeproductbom v-if="carftForm.doType == '2' || carftForm.doType == '3'" ref="Routeproductbom" :carftForm="carftForm" :routeId="carftForm.routeId" :productId="carftForm.productId" :workorderCode="carftForm.workorderCode" :processId="process.processId" :processName="process.processName" :processCode="process.processCode" :buttonType="'2'" :optType="optType" @backEndData="getSubassembly" :subassemblyList="subassemblyList" :bomItemCode="carftForm.bomItemCode" :workorderId="carftForm.workorderId">
          </Routeproductbom>
        </el-tab-pane>
      </el-tabs>
      <el-empty v-else description="该生产工单缺少工艺路径的维护，请先维护工艺路径！！！" image-size="50"></el-empty>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="cancel" v-if="optType == 'view'">返回</el-button>
        <el-button type="primary" @click="submitForms" v-else>保 存</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 生成领料单页面 -->
    <ProcessMaintenance v-if="openRequisitionDetail" ref="processMaintenance" @getList="getList"></ProcessMaintenance>
    <!-- 生成汇报单 -->
    <Debriefing v-if="openDebriefingDetail" ref="debriefings" @getList="getList"></Debriefing>
    <!-- 确认生产 -->

    <!-- BOM变更 -->
    <BomAlter v-if="openBom" ref="bomAlters" @getList="getList"></BomAlter>

    <!-- 产线停产 -->
    <LineStop v-if="openLineStop" ref="lineStops" @getList="getList"></LineStop>

    <!-- 终止 -->
    <EndReason v-if="openEnd" ref="endReasons" @getList="getList"></EndReason>
    <workTimeRecordVue ref="worktimerecord" :workTimeDialog="false" :workorderId="workorderId"></workTimeRecordVue>

    <!-- add begin by zyj 2024/10/22 增加审核 -->
    <Audit ref="audit"></Audit>
    <!-- add end by zyj 2024/10/22 增加审核 -->
    <!-- add begin by zyj 2024/10/29 在生产工单 操作列，增加“生产补料”  -->
    <AddMaterialSupply ref="supplyDetail"></AddMaterialSupply>
    <!--  add end by zyj 2024/10/29 在生产工单 操作列，增加“生产补料” -->
    <!-- 生产退料按钮弹框 -->
    <BackProduction ref="backProductionDetail"></BackProduction>

    <!-- 2024-11-27 新增 成品改制 弹出框 -->
    <FinishedProductReform ref="finishedProductReformRef"></FinishedProductReform>
    <!-- 2024-11-29 新增 成品改制详情 弹出框 -->
    <FinishedProductReformInfo ref="finishedProductReformInfoRef"></FinishedProductReformInfo>
    <!-- 2024-12-18 新增  业务查询：用料清单查询，物料出库查询  弹出框-->
    <workorderBomLinelist ref="workorderBomLinelistRef"></workorderBomLinelist>
    <MaterialOutboundlist ref="materialOutboundlistRef"></MaterialOutboundlist>
    <!-- 2024-12-19 新增 复制BOM版本  弹出框 -->
    <CopyBom ref="copyBomRef"></CopyBom>
  </div>
</template>

<script>
import { getBomworkorder } from "@/api/mes/pro/routeproductbom";
import { printSn } from "@/api/mes/pro/workorderSn";
import {
  listWorkorder,
  getWorkorder,
  delWorkorder,
  addWorkorder,
  updateWorkorder,
  getJdyWorkorder,
  WorkorderRunStatus,
  addRouteCommit,
  updateRouteOrLine,
  addRouteproductbom,
  //add begin by zyj 2024/10/17 产品名称支持模糊搜索下拉
  getProductNameList,
  //add end by zyj 2024/10/17 产品名称支持模糊搜索下拉
  //add begin by zyj 2024/10/22 增加审核
  getRouteId,
  //add end by zyj 2024/10/22 增加审核
  generateReport,
  getReceivedNumByWorkorderId,
  selectUserRole,
  pushDownWorkorder,
  worderDelayTime, // 申请延期
  getBomtemplate,
  addByErp,
} from "@/api/mes/pro/workorder";
import Routeproductbom from "@/views/mes/pro/proroute/routeproductbom";
import RouteproductMain from "./components/routeproductbom.vue";
import { getLineByWorkshopId } from "@/api/mes/md/line";
import { proBOMList, routeBOMList } from "@/api/mes/md/bom";
import Workorderbom from "./bom/bom.vue";
import WorkorderItemList from "./items/item.vue";
import Replenishment from "./items/replenishment.vue";
import ReturnPiece from "./items/returnPiece.vue";
import Material from "./items/material.vue";
import ReportForm from "./items/reportForm.vue";
import Returned from "./items/returned.vue";
import RouteproductbomDetail from "./items/routeproductbomDetail.vue";
import ItemSelect from "@/components/itemSelect/single.vue";
import ClientSelect from "@/components/clientSelect/single.vue";
import { genCode } from "@/api/mes/md/rule";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
// add begin by zyj 2024/10/29 在生产工单 操作列，增加“生产补料”
import AddMaterialSupply from "./components/addMaterialSupply.vue";
// add end by zyj 2024/10/29 在生产工单 操作列，增加“生产补料”
// 生成领料单页面
import ProcessMaintenance from "./components/processMaintenance.vue";
import Debriefing from "./components/debriefing.vue";
import BomAlter from "./components/bomaAlter.vue";
import LineStop from "./components/lineStop.vue";
import EndReason from "./components/endReason.vue";
// 审核记录
import CheckRecord from "./components/checkRecord.vue";
import {
  synchronousDataAcquisition,
  listWorkshop,
} from "@/api/mes/md/workshop";
import Routeprocess from "../proroute/routeprocess.vue";

import { addWorkorderSn } from "@/api/mes/pro/workorderSn";

import { addIssueheader } from "@/api/mes/wm/issueheader";

import workTimeRecordVue from "./components/workTimeRecord.vue";
//add begin by zyj 2024/10/22 增加审核
import Audit from "./components/audit.vue";
//add end by zyj 2024/10/22 增加审核
import BackProduction from "./components/backProduction.vue";//生产退料按钮弹框
/* 2024-11-27 djj 新增 成品改制 弹出框 */
import FinishedProductReform from "./components/finishedProductReform.vue";
/* 2024-11-27 djj 新增 成品改制 弹出框 */
import FinishedProductReformInfo from "./components/finishedProductReformInfo.vue";
import workorderBomLinelist from "./components/workorderBomLinelist.vue";
import MaterialOutboundlist from "./components/materialOutboundlist.vue";
import CopyBom from "./components/copyBom.vue";
export default {
  name: "Workorder",
  dicts: [
    "mes_workorder_status",
    "mes_order_status",
    "mes_order_type",
    "mes_workorder_sourcetype",
    "mes_workorder_runStatus",
    "mes_route_status",
    "workflow_status",
  ],
  components: {
    // 2024-12-19 djj 新增 复制BOM版本
    CopyBom,
    //  2024-12-18 djj 新增  业务查询：用料清单查询，物料出库查询
    workorderBomLinelist, MaterialOutboundlist,
    // 2024-11-29 djj 新增成品改制详情弹出框
    FinishedProductReformInfo,
    // 2024-11-27 djj 新增成品改制弹出框
    FinishedProductReform,
    // 2024/11/15 生产退料
    BackProduction,
    //add begin by zyj 2024/10/22 增加审核
    Audit,
    //add end by zyj 2024/10/22 增加审核
    //add begin by zyj 2024/10/29 在生产工单 操作列，增加“生产补料”
    AddMaterialSupply,
    //add end by zyj 2024/10/29 在生产工单 操作列，增加“生产补料”
    Treeselect,
    ItemSelect,
    Routeproductbom,
    ClientSelect,
    Workorderbom,
    WorkorderItemList,
    Routeprocess,
    RouteproductbomDetail,
    Replenishment,
    Returned,
    Material,
    ReportForm,
    ProcessMaintenance,
    Debriefing,
    RouteproductMain,
    CheckRecord,
    BomAlter,
    LineStop,
    EndReason,
    workTimeRecordVue,
    ReturnPiece,
  },
  data() {
    return {
      //add begin by zyj 2024/10/17 产品名称支持模糊搜索下拉
      productNameList: [],
      //add end by zyj 2024/10/17 产品名称支持模糊搜索下拉
      workTimeDialog: false,
      workorderId: null,
      //子组件传过来的数据
      subassemblyList: [],
      // 工艺维护弹窗
      openCraft: false,
      checkrecordOpen: false,
      // 工艺维护表单参数
      carftForm: { isRemake: 0 },
      // 领料单弹窗
      openRequisition: false,
      openRequisitionDetail: false,
      openDebriefingDetail: false,
      openLineStop: false,
      warehouseList: [],
      // 领料单表单参数
      requisitionForm: {},
      workorderDataList: [],
      openBom: false,

      // 工单工艺路线列表
      carftList: [],
      //自动生成编码
      autoGenFlag: false,
      optType: undefined,
      proNum: undefined,
      // 遮罩层
      loading: false,
      //当前工艺中配置的工序清单
      processList: [],
      // 汇报单列表
      proWorkorderBatchReportList: [],
      // 显示搜索条件
      showSearch: true,
      // 非单个禁用
      single: true,
      // 总条数
      total: 0,
      //tableTotal
      tableTotal: 0,
      // 非多个禁用
      multiple: true,
      // 生产工单表格数据
      workorderList: [],
      productRequisitionData: undefined,
      // 生产工单选择产线
      lineOpts: [],
      //生产车间的list
      workshopList: [],
      //根据车间id获取的产线list
      productionlineList: [],
      lineIds: [],
      // 生产工单树选项
      workorderOptions: [],
      domsg: undefined,
      domsg1: undefined,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      openEnd: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        versionChangeState: null,
        pageSize: 50,
        workorderCode: null,
        workorderId: null,
        workorderName: null,
        orderSource: null,
        sourceCode: null,
        productId: null,
        productCode: null,
        productName: null,
        productSpc: null,
        unitOfMeasure: null,
        quantity: null,
        quantityProduced: null,
        quantityChanged: null,
        quantityScheduled: null,
        clientId: null,
        clientCode: null,
        clientName: null,
        requestDate: null,
        parentId: null,
        ancestors: null,
        //add begin by zyj 2024/10/17 查询条件增加类型
        orderType: null,
        //add end by zyj 2024/10/17 查询条件增加类型
        status: null,
        workflowStatus: null,
        fDate: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        workorderCode: [
          { required: true, message: "工单编号不能为空", trigger: "blur" },
        ],
        workorderName: [
          { required: true, message: "工单名称不能为空", trigger: "blur" },
        ],
        orderSource: [
          { required: true, message: "来源类型不能为空", trigger: "blur" },
        ],
        productId: [
          { required: true, message: "产品不能为空", trigger: "blur" },
        ],
        productCode: [
          { required: true, message: "产品编号不能为空", trigger: "blur" },
        ],
        productName: [
          { required: true, message: "产品名称不能为空", trigger: "blur" },
        ],
        quantity: [
          { required: true, message: "生产数量不能为空", trigger: "blur" },
        ],
        requestDate: [
          { required: true, message: "需求日期不能为空", trigger: "blur" },
        ],
        productNum: [
          { required: true, message: "领料数量不能为空", trigger: "blur" },
        ],
        warehouseId: [
          { required: true, message: "领料仓库不能为空", trigger: "blur" },
        ],
      },
      rulesa: {
        // workorderCode: [
        //   { required: true, message: "工单编号不能为空", trigger: "blur" },
        // ],
        // workorderName: [
        //   { required: true, message: "工单名称不能为空", trigger: "blur" },
        // ],
        // orderSource: [
        //   { required: true, message: "来源类型不能为空", trigger: "blur" },
        // ],
        // productId: [
        //   { required: true, message: "产品不能为空", trigger: "blur" },
        // ],
        // productCode: [
        //   { required: true, message: "产品编号不能为空", trigger: "blur" },
        // ],
        // productName: [
        //   { required: true, message: "产品名称不能为空", trigger: "blur" },
        // ],
        // quantity: [
        //   { required: true, message: "生产数量不能为空", trigger: "blur" },
        // ],
        // requestDate: [
        //   { required: true, message: "需求日期不能为空", trigger: "blur" },
        // ],
        // productNum: [
        //   { required: true, message: "领料数量不能为空", trigger: "blur" },
        // ],
        // warehouseId: [
        //   { required: true, message: "领料仓库不能为空", trigger: "blur" },
        // ],
        // workshopId: [
        //   { required: true, message: "生产车间不能为空", trigger: "blur" }
        // ],
        // lineId: [
        //   { required: true, message: "生产产线不能为空", trigger: "blur" }
        // ],
        // actualStartTime: [
        //   { required: true, message: "实际开工时间不能为空", trigger: "blur" }
        // ],
        // actualFinisihTime: [
        //   { required: true, message: "实际完工时间不能为空", trigger: "blur" }
        // ]
      },
      rulesb: {
        productNum: [
          { required: true, message: "领料数量不能为空", trigger: "blur" },
          { type: "number", min: 1, message: "领料数量不能低于1" },
        ],
      },
      rulesc: {
        workshopId: [
          { required: true, message: "生产车间不能为空", trigger: "blur" },
        ],
        lineId: [
          { required: true, message: "生产产线不能为空", trigger: "blur" },
        ],
        productType: [
          { required: true, message: "生产类型不能为空", trigger: "blur" },
        ],
      },
      openDetail: false,
      defaultAll: false,
      //选择bom信息下拉框
      optionsChildren: [],
      //下拉框的ids
      value: [],
      //下拉框的值
      valueChildren: "",
      currentRow: null,
      activeName: 'routeproductbomDetailRef0',
      activeName2: 'productbom0',
      routeproductbomRefType: 'productbom'
    };
  },
  created() {
    this.getList();
    this.remoteGetProductNameList();
    this.$nextTick(() => {
      this.$refs.curdRef && this.$refs.curdRef.doLayout();
    });
  },

  methods: {
    //add begin by zyj 2024/10/29 在生产工单 操作列，增加“生产补料”
    toSupplyDetail(row) {

      this.$nextTick(() => {
        this.$refs.supplyDetail.init({ bomItemCode: row.bomItemCode, workorderCode: row.workorderCode, workorderId: row.workorderId });
      });
    },
    //add end by zyj 2024/10/29 在生产工单 操作列，增加“生产补料”
    //add begin by zyj 2024/10/22 增加审核
    toRouteAudit(row) {
      this.loading = true
      getRouteId(row.workorderId).then(res => {
        if (res.recordId) {
          this.$refs['audit'].init({ routeId: res.routeId, recordId: res.recordId, bomItemCode: row.bomItemCode, workorderId: row.workorderId })
          this.loading = false
        } else {
          this.loading = false
          this.$message.warning('该工单没有工艺路线')
        }
      })
    },
    //add end by zyj 2024/10/22 增加审核
    //add begin by zyj 2024/10/17 产品名称支持模糊搜索下拉
    onClearProductName() {
      this.remoteGetProductNameList();
    },
    remoteGetProductNameList(productName) {
      this.productNameListLoading = true;
      getProductNameList({ productName: productName }).then(res => {
        this.productNameList = res.data;
        this.productNameListLoading = false;
      })
    },
    //add end by zyj 2024/10/17 产品名称支持模糊搜索下拉
    toWorkingRecord(row) {
      this.$refs.worktimerecord.handleAddRecord(row.workorderId);
    },
    // 打印条码
    print(row) {
      console.log(row);
      printSn(row).then((response) => {
        if (response.code == 200) {
          this.$modal.msgSuccess("打印成功");
        } else {
          this.$modal.msgError("打印失败");
        }
      });
    },
    //获取子组件数据
    getSubassembly(msg, type) {
      console.log(msg, type, "祖父组件msg");
      if (type == "add" && msg) {
        msg.forEach((item) => {
          //edit begin by zyj 2024/10/17 未选物料放列表最上面
          if (item != undefined) {

            this.subassemblyList.push(item);
          }

          //edit end by zyj 2024/10/17 未选物料放列表最上面
        });
        console.log(this.subassemblyList, "祖父组件数据");
      } else if (type == "del") {
        this.subassemblyList = this.subassemblyList.filter(
          (_) => _.itemCode != msg.itemCode
        );
        console.log(this.subassemblyList, "祖父组件数据11111");
      }

      // if (msg != null || msg != undefined) {
      //   this.subassemblyList = this.subassemblyList.concat(msg)
      //   console.log(this.subassemblyList, "子组件数据");
      // }
    },
    /** 查询生产工单列表 */
    getList() {
      this.loading = true;
      listWorkorder(this.queryParams).then((response) => {
        this.workorderList = this.handleTree(
          response.rows,
          "workorderId",
          "parentId"
        );
        this.total = response.total;
        this.loading = false;
      }).catch(() => {
        this.loading = false;
      });
    },
    /** 转换生产工单数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.workorderId,
        label: node.workorderName,
        children: node.children,
      };
    },
    /** 查询生产工单下拉树结构 */
    getTreeselect() {
      listWorkorder().then((response) => {
        this.workorderOptions = [];
        const data = {
          workorderId: 0,
          workorderName: "顶级节点",
          children: [],
        };
        data.children = this.handleTree(
          response.rows,
          "workorderId",
          "parentId"
        );
        this.workorderOptions.push(data);
      });
    },
    /* 工单详情-取消弹框按钮 */
    cancelDetail() {
      this.openDetail = false;
      this.activeName = 'routeproductbomDetailRef0'
      this.reset();
    },
    // 取消按钮
    cancel() {
      this.reset();
      this.openCraft = false;
      this.openRequisition = false;
      this.open = false;
      this.openDetail = false;

    },
    // 表单重置
    reset() {
      this.form = {
        workorderId: null,
        workorderCode: null,
        workorderName: null,
        orderSource: null,
        sourceCode: null,
        productId: null,
        productCode: null,
        productName: null,
        productSpc: null,
        unitOfMeasure: null,
        quantity: null,
        quantityProduced: null,
        quantityChanged: null,
        quantityScheduled: null,
        clientId: null,
        clientCode: null,
        clientName: null,
        requestDate: null,
        parentId: null,
        status: 0,
        remark: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        orderType: null,
        fPlanStartDate: null,
        fPlanFinishDate: null,
      };
      this.autoGenFlag = false;
      this.value = [];
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    //从BOM行中直接新增
    handleSubAdd(row) {
      this.open = false;
      this.reset();
      this.getTreeselect();
      if (row != null && row.workorderId) {
        this.form = row;
        this.form.parentId = row.workorderId;
        this.form.workorderId = null;
        this.form.workorderCode = null;
      } else {
        this.form.parentId = 0;
      }
      this.open = true;
      this.title = "添加生产工单";
      this.optType = "add";
    },
    /** 同步数据按钮操作 */
    async handleSet() {
      try {
        this.loading = true;
        const response = await getJdyWorkorder(0);
        console.info("response.data", response.data);
        if (response.code === 200) {
          this.$message({
            message: "数据同步成功",
            type: "success",
          });
        } else {
          throw new Error("数据同步失败");
        }
      } catch (err) {
        this.$message.error(err.message);
      } finally {
        this.loading = false;
      }
    },
    /** 新增按钮操作 */
    handleAdd(row) {
      this.reset();
      this.getTreeselect();
      if (row != null && row.workorderId) {
        this.form.parentId = row.workorderId;
        this.form.orderSource = row.orderSource;
        this.form.sourceCode = row.sourceCode;
        this.form.clientId = row.clientId;
        this.form.clientCode = row.clientCode;
        this.form.clientName = row.clientName;
      } else {
        this.form.parentId = 0;
      }
      this.open = true;
      this.title = "添加生产工单";
      this.optType = "add";
    },
    /* 查看详情-工艺维护tabs */
    handleClick(tab, event) {
      this.activeName = 'routeproductbomDetailRef' + tab.index
      this.$refs['routeproductbomDetailRef'][tab.index].init()
    },
    // 查询明细按钮操作
    handleView(row) {
      this.loading = true
      this.reset();
      // this.getTreeselect();
      const workorderId = row.workorderId || this.ids;
      getWorkorder(workorderId).then((response) => {
        console.log(response, "查询明细res");
        this.form = response.data;
        this.lineOpts = response.lines;
        const routeName = response.routes?.routeName || "";
        const routeId = response.routes?.routeId || "";
        this.processList = response.proRouteProcesses || [];
        this.proWorkorderBatchReportList =
          response.proWorkorderBatchReportList || [];
        this.$set(this.form, "proRouteProcesses", response.proRouteProcesses);
        this.$set(this.form, "routeName", routeName);
        this.$set(this.form, "routeId", routeId);
        this.$set(this.form, "routes", response.routes);
        this.$set(this.form, "workorderId", response.data.workorderId);
        this.$set(this.form, "productId", response.data.productId);
        this.$set(this.form, "bomItemCode", response.data.bomItemCode)
        this.$set(this.form, "processId", response.data.processId)

        this.$set(
          this.carftForm,
          "proRouteProcesses",
          response.proRouteProcesses
        );
        this.$set(this.carftForm, "routeName", routeName);
        this.$set(this.carftForm, "routeId", routeId);
        this.$set(this.carftForm, "routes", response.routes);
        this.$set(this.carftForm, "workorderId", response.data.workorderId);
        this.$set(this.carftForm, "productId", response.data.productId);
        this.$set(this.carftForm, "bomItemCode", response.data.bomItemCode)
        this.$set(this.carftForm, "processId", response.data.processId)
        console.log(this.form, "=======this.form=========");
        this.openDetail = true;
        this.title = "查看工单信息";
        // 审批记录
        this.checkrecordOpen = true;
        this.$nextTick(() => {
          if (this.processList && this.processList.length > 0) {
            this.$refs['routeproductbomDetailRef'][0].init()
          }
          this.$refs.checkrecords.init(row);
        });
        this.loading = false
        // this.optType = "view";
      }).catch(err => {
        this.loading = false
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.getTreeselect();
      if (row != null) {
        this.form.parentId = row.workorderId;
      }
      getWorkorder(row.workorderId).then((response) => {
        this.form = response.data;
        this.lineOpts = response.lines;
        this.$set(this.form, "lineIds", response.lineIds);
        this.open = true;
        this.title = "绑定生产产线";
        this.optType = "edit";
      });
    },
    /** 领料单生产按钮操作 */
    handleRequisition(row) {
      /* 老逻辑 */
      this.reset();
      // this.openRequisitionDetail = true;
      // console.log(row, "领料单编号的row");
      // this.$nextTick(() => {
      //   this.$refs.processMaintenance.init(row);
      // });
      /* 新逻辑 */

      this.$confirm("是否生成领料单", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        console.log(row);
        // return;
        addByErp({
          workorderId: row.workorderId,
          productId: row.productId,
          workorderQuantity: row.quantity,
        }).then((res) => {
          if (res.code == 200) {
            this.$message.success("生成领料单成功！");
          }
        });
      });

      // this.reset();
      // this.getTreeselect();
      // if (row != null) {
      //   this.requisitionForm.parentId = row.workorderId;
      // }
      // getWorkorder(row.workorderId).then((response) => {
      //   this.requisitionForm = response.data;
      //   this.openRequisition = true;
      //   this.title = "生成领料单";
      //   this.optType = "edit";
      //   this.warehouseList = response.warehouseList || [];
      //   this.queryParams.productId = this.requisitionForm.productId;
      //   this.queryParams.workorderId = row.workorderId;
      //   this.productRequisitionData = this.requisitionForm;
      //   // 获取领料数量
      //   // getReceivedNumByWorkorderId(row.workorderId).then((response) => {
      //   //   this.requisitionForm.receivedNum = response.data;
      //   //   Vue.set(this.requisitionForm, "receivedNum", response.data);
      //   // });
      //   proBOMList(this.queryParams).then((res) => {
      //     console.info("response", res);
      //     for(var i=0;i<res.data.length;i++){
      //       res.data[i].productNumMax = res.data[i].productNum = (this.requisitionForm.quantity * res.data[i].jdyNumerator).toFixed(2)
      //     }
      //     this.workorderDataList = res.data;
      //     this.loading = false;
      //     this.getSpanArr(res.data || []);
      //     this.productRequisitionData.mdProductBomList = this.workorderDataList;
      //   });

      //   // routeBOMList(this.queryParams).then(response => {
      //   //   console.log('response.rows====bom====>222', response)
      //   //   this.workorderDataList = response.rows;
      //   //   this.total = response.total;
      //   //   this.loading = false;
      //   //   // this.productRequisitionData = {...this.requisitionForm};
      //   //   this.productRequisitionData = this.requisitionForm;

      //   // });
      // });
    },
    // 生成汇报单
    handleDebriefing(row) {
      this.reset();
      this.openDebriefingDetail = true;
      console.log(row, "领料单编号的row");
      this.$nextTick(() => {
        this.$refs.debriefings.init(row);
      });
    },
    // bom变更
    handleBom(row) {
      this.openBom = true;
      this.reset();
      this.$nextTick(() => {
        this.$refs.bomAlters?.init(row);
      });
      // if (row.orderTypeName === "返工生产") {
      //   this.$confirm('请确认生产退料是否已完成?', '提示', {
      //     confirmButtonText: '确定',
      //     cancelButtonText: '取消',
      //     type: 'warning'
      //   }).then(() => {
      //     this.openBom = true;
      //     this.executeBomUpdate(row);
      //   }).catch(() => {
      //     this.openBom = false;
      //   });
      // } else {
      //   this.openBom = true;
      //   this.executeBomUpdate(row);
      // }
    },

    // 工艺路径维护表单重置
    resetCarft() {
      this.carftForm = {
        workorderId: null,
        workorderCode: null,
        workorderName: null,
        orderSource: null,
        sourceCode: null,
        productId: null,
        productCode: null,
        productName: null,
        productSpc: null,
        unitOfMeasure: null,
        quantity: null,
        quantityProduced: null,
        quantityChanged: null,
        quantityScheduled: null,
        clientId: null,
        clientCode: null,
        clientName: null,
        requestDate: null,
        parentId: null,
        status: 0,
        remark: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        orderType: null,
        fPlanStartDate: null,
        fPlanFinishDate: null,
        doType: null,
      };
      this.autoGenFlag = false;
      this.subassemblyList = [];
      this.resetForm("carftForm");
    },
    //  工艺维护 确认生产 申请延期
    statusQuery(row, type) {
      this.loading = true; // 开启加载状态，防止页面卡顿

      localStorage.removeItem("Ids"); // 清除本地存储的 ID，防止上次数据残留
      this.resetCarft(); // 重置工艺相关数据
      this.getTreeselect(); // 获取生产工单下拉树结构
      this.getworkshopList(); // 获取车间集合

      if (row != null) {
        this.carftForm.parentId = row.workorderId; // 记录当前操作的工单 ID
      }

      // 当 `type` 不是 "1" 时，直接查询工单信息
      if (type !== "1") {
        getWorkorder(row.workorderId).then((response) => {
          if (!response) return; // 如果请求失败或无数据，则直接返回

          console.log(response, "详情res"); // 打印返回数据
          this.carftForm = response.data || {}; // 赋值工艺表单数据
          this.carftForm.actualStartTime = this.carftForm.actualStartTime || this.carftForm.fplanStartDate; // 处理 `actualStartTime` 为空的情况
          this.carftForm.doType = type; // 记录操作类型
          this.lineOpts = response.lines; // 设置生产线选项

          // 如果 `lineId` 不是空，则转换为数组
          if (response.data.lineId) {
            this.carftForm.lineId = response.data.lineId.split(",").map(Number);
          }

          this.$set(this.carftForm, "lineIds", response.lineIds); // 设置 `lineIds` 绑定数据
          this.processList = response.proRouteProcesses || []; // 赋值工艺流程数据

          if (this.carftForm.workshopId) {
            this.selectTrigger(this.carftForm.workshopId); // 触发车间选择
          }

          this.$set(this.carftForm, "proRouteProcesses", response.proRouteProcesses);
          this.$set(this.carftForm, "routeName", response.routes?.routeName);
          this.$set(this.carftForm, "routeId", response.routes?.routeId);
          this.$set(this.carftForm, "routes", response.routes);

          this.$set(this.carftForm, "workorderId", response.data.workorderId);
          this.$set(this.carftForm, "productId", response.data.productId);
          this.$set(this.carftForm, "bomItemCode", response.data.bomItemCode)
          this.$set(this.carftForm, "processId", response.data.processId)

          // 根据 `type` 设置弹窗标题
          this.title = type === "1" ? "工艺路线维护" : type === "2" ? "确认生产" : "申请延期";
          this.optType = "edit"; // 设置操作类型
          this.$nextTick(() => {
            console.log("type", this.routeproductbomRefType, this.$refs[this.routeproductbomRefType])
            if (this.$refs[this.routeproductbomRefType] && this.$refs[this.routeproductbomRefType].length > 0) {
              this.$refs[this.routeproductbomRefType][0].init()
            }
          })
          return this.getTemplate(type); // 获取工艺模板数据
        }).finally(() => {
          this.loading = false; // 结束加载状态
        });

        return;
      }

      let route_id = null;
      getRouteId(row.workorderId).then(res => {
        if (!res.recordId) {
          this.$message.warning("请先配置工艺路线"); // 提示用户工艺路线未配置
          throw new Error("未配置工艺路线"); // 终止后续操作
        }
        route_id = res.routeId; // 记录 `routeId`
        return getWorkorder(row.workorderId); // 继续查询工单信息
      }).then((response) => {
        if (!response) return; // 无数据时直接返回

        this.carftForm = response.data || {}; // 赋值表单数据
        this.carftForm.actualStartTime = this.carftForm.actualStartTime || this.carftForm.fplanStartDate; // 处理 `actualStartTime` 为空的情况
        this.carftForm.doType = type; // 记录操作类型
        this.carftForm.routeId = route_id; // 设置 `routeId`
        this.lineOpts = response.lines; // 设置生产线数据

        // 确认生产时处理 `lineId`
        if (type === "2" && response.data.lineId) {
          this.carftForm.lineId = response.data.lineId.split(",").map(Number);
        }

        this.$set(this.carftForm, "lineIds", response.lineIds); // 设置 `lineIds` 绑定数据
        this.processList = response.proRouteProcesses || []; // 赋值工艺流程数据

        if (this.carftForm.workshopId) {
          this.selectTrigger(this.carftForm.workshopId); // 触发车间选择
        }

        this.$set(this.carftForm, "proRouteProcesses", response.proRouteProcesses);
        this.$set(this.carftForm, "routeName", response.routes?.routeName);
        this.$set(this.carftForm, "routeId", response.routes?.routeId);
        this.$set(this.carftForm, "routes", response.routes);
        this.$set(this.carftForm, "workorderId", response.data?.workorderId);
        this.$set(this.carftForm, "productId", response.data.productId);
        this.$set(this.carftForm, "bomItemCode", response.data?.bomItemCode);
        this.$set(this.carftForm, "processId", response.data.processId)

        // 根据 `type` 设置弹窗标题
        this.title = type === "1" ? "工艺路线维护" : type === "2" ? "确认生产" : "申请延期";
        this.optType = "edit"; // 设置操作类型
        this.$nextTick(() => {
          console.log("type", this.routeproductbomRefType, this.$refs[this.routeproductbomRefType])
          if (this.$refs[this.routeproductbomRefType] && this.$refs[this.routeproductbomRefType].length > 0) {
            this.$refs[this.routeproductbomRefType][0].init()
          }
        })
        return this.getTemplate(type); // 获取工艺模板数据
      }).finally(() => {
        this.loading = false; // 确保无论请求是否成功，都关闭 `loading`
      }).catch(() => { });
    },
    /* 工艺维护 确认生产 申请延期 弹框 -工艺维护tabs */
    handleClick2(tab, event) {
      this.activeName2 = this.routeproductbomRefType + tab.index
      this.$refs[this.routeproductbomRefType][tab.index].init()
    },
    /** type: 1、工艺维护 2、确认生产 3、申请延期 按钮操作 */
    handleUpdateRoute(row, type, name) {

      this.statusQuery(row, type)

      this.$nextTick(() => {
        if (type == 1) {
          this.routeproductbomRefType = "productbom"
          this.activeName2 = 'productbom0'
        }
        if (type == 2 || type == 3) {
          this.routeproductbomRefType = "Routeproductbom"
          this.activeName2 = 'Routeproductbom0'
        }
        // setTimeout(() => {
        //   console.log("type", this.routeproductbomRefType, this.$refs[this.routeproductbomRefType])
        //   if (this.$refs[this.routeproductbomRefType] && this.$refs[this.routeproductbomRefType].length > 0) {
        //     this.$refs[this.routeproductbomRefType][0].init()
        //   }
        // }, 3000)
      })
      // selectUserRole(name)
      //   .then((res) => {
      //     this.statusQuery(row, type);
      //   })
      //   .catch(() => {
      //     console.log("qqqqqqqqq");
      //     return "false";
      //   });
    },
    //获取模板id
    getTemplate(type) {
      this.openCraft = true; // 打开工艺维护弹窗
      if (!this.carftForm.routeId) return; // 如果 `routeId` 为空，直接返回

      let params = {
        routeId: this.carftForm.routeId, // 传递 `routeId`
        bomItemCode: this.carftForm.bomItemCode, // 传递 `bomItemCode`
      };

      return getBomworkorder(params).then((res) => {
        if (res.code !== 200) return; // 如果返回状态不是 200，则终止操作

        // 如果 `type` 是 "1" 且审核状态为空，则提示用户等待审核通过
        if (type === "1" && !res.data[0]?.children[0]?.auditStatus) {
          this.$message.warning("请等待工艺路线审核通过之后，再进行工艺维护");
          throw new Error("工艺路线未审核通过"); // 终止操作
        }

        // 处理数据，转换成级联选择器格式
        this.optionsChildren = res.data.map((item) => ({
          value: item.recordId, // 工艺 ID
          label: item.itemName, // 工艺名称
          children: item.children.map((child) => ({
            value: child.versionsId, // 版本 ID
            label: child.versionsName, // 版本名称
          })),
        }));


      }).finally(() => {
        this.loading = false; // 确保 `loading` 关闭
      }).catch(() => {
        this.loading = false; // 确保 `loading` 关闭
      });
    },

    //选择bom信息下拉框的change
    handleChange(value) {
      this.valueChildren = value[value.length - 1];
      console.log("value", value);
      let param = {
        workorderId: this.carftForm.workorderId,
        versionsId: this.valueChildren,
      };
      getBomtemplate(param).then((res) => {
        if (res.code == 200) {
          this.$nextTick(() => {
            if (this.$refs[this.routeproductbomRefType] && this.$refs[this.routeproductbomRefType].length > 0) {
              this.$refs[this.routeproductbomRefType][0].init()
            }
          })
          //调子组件刷新方法
          /* this.$refs.productbom.forEach((item) => {
            this.$nextTick(() => {
              item.init();
            });
          }); */
        }
      });
    },
    // 按钮权限
    // permissions(row, name, type) {
    //   selectUserRole(name)
    //     .then((res) => {
    //       if (type == "debriefing") {
    //         // 生成汇报单
    //         this.handleDebriefing(row);
    //       } else if (type == "picking") {
    //         // 领料单
    //         this.handleRequisition(row);
    //       } else if (type == "production") {
    //         // 产线停产
    //         this.openLineStop = true;
    //         console.log(row, "bom变更的row");
    //         this.$nextTick(() => {
    //           this.$refs.lineStops.init(row);
    //         });
    //         // this.updateRunStatus(row);
    //       }
    //     })
    //     .catch(() => {
    //       console.log("qqqqqqqqq");
    //       return "false";
    //     });
    // },
    // 终止
    endQuery(row) {
      // 产线停产
      this.openEnd = true;
      //console.log(row, "bom变更的row");
      this.$nextTick(() => {
        this.$refs.endReasons.init(row);
      });
    },
    //获取车间集合
    getworkshopList() {
      listWorkshop().then((res) => {
        //console.log(res, "车间集合list");
        if (res.code == 200) {
          this.workshopList = res.data;
        }
      });
    },
    //根据车间id获取生产产线
    selectTrigger(id) {
      //console.log(id, "车间的id");
      getLineByWorkshopId(id).then((res) => {
        console.log(res, "车间下的生产产线");
        if (res.code == 200) {
          this.productionlineList = res.data;
        }
      });
    },

    //生成SN码
    handleCreateSn(row) {
      if (row != null) {
        this.carftForm.parentId = row.workorderId;
      }
      getWorkorder(row.workorderId).then((response) => {
        this.carftForm = response.data;
        this.$set(this.carftForm, "lineIds", response.lineIds);
        this.$set(this.carftForm, "routeName", response.routes.routeName);
        this.$set(this.carftForm, "routeId", response.routes.routeId);
        this.form.productId = this.carftForm.productId;
        this.form.bomItemCode = this.carftForm.bomItemCode;
        this.form.productCode = this.carftForm.productCode;
        this.form.productName = this.carftForm.productName;
        this.form.productSpec = this.carftForm.productSpc;
        this.form.productUnit = this.carftForm.unitOfMeasure;
        this.form.workshopId = this.carftForm.workshopId;
        this.form.workshopName = this.carftForm.workshopName;
        this.form.workorderId = this.carftForm.workorderId;
        this.form.workorderCode = this.carftForm.workorderCode;
        this.form.workorderTime = this.carftForm.fplanStartDate;
        this.form.workorderBatch = this.carftForm.batchCode;
        this.form.lineIds = this.carftForm.lineId;
        this.form.routeId = this.carftForm.routeId;
        this.form.routeName = this.carftForm.routeName;
        this.form.number = this.carftForm.quantity;
        addWorkorderSn(this.form).then((response) => {
          this.$modal.msgSuccess("操作成功,可前往工单SN页面查看！");
          this.open = false;
          this.getList();
        });
      });
    },
    submitForms() {
      this.$modal
        .confirm("是否确认保存？")
        .then(() => {
          console.log("确定");
          this.$refs.carftForm.validate((valid) => {
            if (valid) {
              console.log(this.carftForm, "保存时的数据");
              if (this.carftForm.doType == "2") {
                // 确认生产
                let list = this.productionlineList.filter(
                  (_) => _.lineId == this.carftForm.lineId.join(","),
                  _.workshopName == this.carftForm.workshopName
                );
                console.log(this.productionlineList, "this.productionlineList");
                console.log(list, "list");
                this.carftForm.lineName =
                  list && list.length > 0 ? list[0].lineName : "";
                this.carftForm.workshopName =
                  list && list.length > 0 ? list[0].workshopName : "";
                this.carftForm.lineId = this.carftForm.lineId.join(",");
                updateRouteOrLine(this.carftForm).then((response) => {
                  this.$modal.msgSuccess("保存成功");
                  this.openCraft = false;
                  this.getList();
                  this.cancelCarft();
                });
              } else if (this.carftForm.doType == "1") {
                // 工艺维护
                this.carftForm.lineId = null;
                this.subassemblyList.forEach((item) => {
                  item.jdyNumerator = Number(item.jdyNumerator);
                });
                this.carftForm.subassemblyList = this.subassemblyList;
                delete this.carftForm.proRouteProcesses;
                addRouteCommit(this.carftForm).then((response) => {
                  this.$modal.msgSuccess("保存成功");
                  this.openCraft = false;
                  this.getList();
                  this.cancelCarft();
                });
              } else if (this.carftForm.doType == "3") {
                // 申请延期
                this.carftForm.lineId = null;
                worderDelayTime(this.carftForm).then((response) => {
                  this.$modal.msgSuccess("延期成功");
                  this.openCraft = false;
                  this.getList();
                  this.cancelCarft();
                });
              }
            }
          });
        })
        .catch(() => { });
    },

    /** 提交按钮 */
    submitForm() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          if (this.form.workorderId != null) {
            updateWorkorder(this.form).then((response) => {
              console.info("this.form", this.form);
              this.$modal.msgSuccess("修改成功");
              //this.open = false;
              //this.$refs["bomlist"].getList();
              this.getList();
            });
          } else {
            addWorkorder(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              //this.open = false;
              this.form.workorderId = response.data;
              this.getList();
            });
          }
        }
      });
    },
    /** 停产按钮操作 */
    updateRunStatus(row) {
      console.info(row.runStatus);
      if (row.runStatus == 0 || row.runStatus == null) {
        this.domsg = "停产";
        this.domsg1 = "已停产！";
      } else if (row.runStatus == 1) {
        this.domsg = "恢复生产";
        this.domsg1 = "已恢复生产！";
      }
      console.info("this.domsg===>", this.domsg);
      console.info("this.domsg111===>", this.domsg1);
      this.$modal
        .confirm(
          '是否确认生产工单编号为"' +
          row.workorderCode +
          '"的工单' +
          this.domsg +
          "?"
        )
        .then(function () {
          return WorkorderRunStatus(row.workorderId);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess(this.domsg1);
        })
        .catch(() => { });
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      this.$modal
        .confirm(
          '是否确认删除生产工单编号为"' + row.workorderId + '"的数据项？'
        )
        .then(function () {
          return delWorkorder(row.workorderId);
        })
        .then(() => {
          this.getList();
          this.$modal.msgError("删除成功");
        })
        .catch(() => { });
    },
    // (row.isIssue == 1 || row.isIssue == 2) &&(row.status == 8 || row.status == 4)
    // 下推
    handlePushDown(row) {
      console.log(this.carftForm.workshopId, "this.carftForm.workshopId");
      console.log(this.carftForm.lineId, "this.carftForm.lineId");
      if (
        (!this.carftForm.workshopId || !this.carftForm.lineId) &&
        this.carftForm.doType == "2"
      ) {
        this.$modal.msgError("未执行确认生产");
        return;
      }
      let query = { ...row };
      query.flowType =
        row.status == 3 && row.workflowStatus == "1"
          ? "gywh"
          : row.status == 8 && row.workflowStatus == "2" && row.routeStatus == 1
            ? "qrsc"
            : row.workflowStatus == "3"
              ? "scll"
              : "";
      this.$modal
        .confirm(
          '是否确认下推生产工单编号为"' + row.workorderCode + '"的数据项？'
        )
        .then(function () {
          return pushDownWorkorder(query);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("下推成功");
        })
        .catch(() => { });
    },
    handleSelectProduct() {
      this.$refs.itemSelect.showFlag = true;
    },
    handleSelectClient() {
      this.$refs.clientSelect.showFlag = true;
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "mes/pro/workorder/export",
        {
          ...this.queryParams,
        },
        `workorder_${new Date().getTime()}.xlsx`
      );
    },
    handleFinish() {
      let that = this;
      this.$modal
        .confirm("是否完成工单编制？【完成后将不能更改】")
        .then(function () {
          that.form.status = 4;
          that.submitForm();
        });
    },
    //物料选择弹出框
    onItemSelected(obj) {
      if (obj != undefined && obj != null) {
        this.form.productId = obj.itemId;
        this.form.productCode = obj.itemCode;
        this.form.productName = obj.itemName;
        this.form.productSpc = obj.specification;
        this.form.unitOfMeasure = obj.unitOfMeasure;
      }
    },
    //客户选择弹出框
    onClientSelected(obj) {
      if (obj != undefined && obj != null) {
        this.form.clientId = obj.clientId;
        this.form.clientCode = obj.clientCode;
        this.form.clientName = obj.clientName;
      }
    },
    //自动生成编码
    handleAutoGenChange(autoGenFlag) {
      if (autoGenFlag) {
        genCode("WORKORDER_CODE").then((response) => {
          this.form.workorderCode = response;
        });
      } else {
        this.form.workorderCode = null;
      }
    },

    // 领料单数量
    measureFun(value) {
      console.log(value, "====value===");
      // measureName
      // workorderDataList
      for (let i = 0; i < this.workorderDataList.length; i++) {
        this.workorderDataList[i].productNum = (
          value * this.workorderDataList[i].jdyNumerator
        ).toFixed(2);
      }
      console.log(this.workorderDataList, "tableList");
      for (
        let i = 0;
        i < this.productRequisitionData.mdProductBomList.length;
        i++
      ) {
        this.productRequisitionData.mdProductBomList.productNum = (
          value * this.productRequisitionData.mdProductBomList[i].jdyNumerator
        ).toFixed(2);
      }
    },

    // 行合并
    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
      if (columnIndex === 1) {
        const _row = this.spanArr[rowIndex]; // 合并行数
        const _col = this.spanArr[rowIndex] > 0 ? 1 : 0; // 合并的列数
        return {
          rowspan: _row,
          colspan: _col,
        };
      }
    },
    // 按照类型合并
    getSpanArr(data) {
      this.spanArr = []; // tip: 后台获取完成数据后，一定要重置spanArr=[],避免出现合并混乱！！！！！
      if (data.length > 0) {
        for (let i = 0; i < data.length; i++) {
          // 当为第一行时
          if (i === 0) {
            this.spanArr.push(1);
            this.pos = 0;
          } else {
            // 判断当前值是否与上一行的【名称】相等，相等则进行合并
            if (data[i].processName === data[i - 1].processName) {
              this.spanArr[this.pos] += 1; // 合并单元格：合并的行数 +1
              this.spanArr.push(0); // 0代表单元格是不需要显示, 已经被合并的单元格
            } else {
              this.spanArr.push(1); // 1代表当前这行的数据需要被显示
              this.pos = i;
            }
          }
        }
      }
    },
    // 领料仓库修改
    fstockChage(value, obj, index) {
      console.log(value, obj, index, "====value,obj,index======-");
      this.workorderDataList[index].fstockName = value;
      this.workorderDataList[index].fbaseQty =
        obj.bdInventoryList.filter((_) => _.fstockName == value)[0]?.fbaseQty ||
        0;
      this.productRequisitionData.mdProductBomList = this.workorderDataList;
    },

    // 2024/11/15 新增 生产退料 按钮
    getBackProduction(row) {
      this.$refs.backProductionDetail.init(row)
    },
    /* 2024-11-27 djj 新增 成品改制 按钮 */
    getFinishedProductReform(row) {
      this.$refs.finishedProductReformRef.init(row)
    },
    /* 2024-11-29 djj 新增 改制详情 按钮 */
    getFinishedProductReformInfo(row) {
      this.$refs.finishedProductReformInfoRef.init(row)
    },
    /* 2024-12-18 djj 新增 单选行事件 */
    handleCurrentChange(val) {
      console.info('单机行', val)
      this.currentRow = val;
    },
    /* 2024-12-18 djj 新增 下拉框选择事件 */
    handleCommand(command) {
      console.info('command', command)
      if (command == '1') {
        this.getWorkorderBomLine()
      }
      if (command == '2') {
        this.getMaterialOutbound()
      }
    },
    /* 2024-12-18 djj 新增 用料清单查询 按钮 */
    getWorkorderBomLine() {
      console.info('11111', this.currentRow, this.$refs)
      if (!this.currentRow || Object.keys(this.currentRow).length === 0) return this.$message.warning('请选择生产工单')
      this.$refs.workorderBomLinelistRef.init(this.currentRow)
    },
    /* 2024-12-18 djj 新增 物料出库查询 按钮 */
    getMaterialOutbound() {
      if (!this.currentRow || Object.keys(this.currentRow).length === 0) return this.$message.warning('请选择生产工单')
      this.$refs.materialOutboundlistRef.init(this.currentRow)
    },
    /* 2024-12-19 djj 新增 复制BOM版本 按钮 */
    getCopyBom(row) {
      this.$refs.copyBomRef.init(row)
    },
  },
};
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
.app-container ::v-deep .el-drawer__header > :first-child {
  font-weight: 700 !important;
  font-size: 20px;
}

.tabsDiv {
  padding: 20px;
  padding-top: 0;
}

.tabsDiv ::v-deep .el-tabs--card > .el-tabs__header .el-tabs__item {
  font-weight: 700;
  font-size: 18px;
}

.drawerFooter {
  text-align: right;
  padding: 20px;
}

.bg-purple {
  display: flex;
  align-items: flex-start;
  justify-content: flex-start;
  // white-space: nowrap;
  line-height: 30px;

  span:nth-child(1) {
    display: inline-block;
    // width: 110px;
    white-space: nowrap;
    // line-height: 30px;
  }
}

.dialog-footer {
  padding-top: 20px;
  text-align: center;
}

.app-container ::v-deep .el-drawer__header {
  padding-top: 10px !important;
  padding-bottom: 5px !important;
  margin-bottom: 10px !important;
}
</style>
